package com.ruyuan.eshop.framework.utils;

import org.springframework.stereotype.Service;

/**
 * Snowflake 实现的发号器
 *
 * @author pwd
 * @version 1.0
 */

@Service
public class SnowflakeSnCreator implements SnCreator {


    /**
     *最大递增序列
     */
    private static final long MAX_SEQ = 4000L;

    /**
     * 起始时间戳
     */
    private static final long START_TIME = 1587092627355L;

    private static long COUNT =0;

    /**
     * 获取递增序列
     * @return
     */
    private  synchronized long getSequence() {
        COUNT++;

        if (COUNT > MAX_SEQ) {
            COUNT =0;
        }

        return COUNT;
    }


    @Override
    public Long create(int subCode) {

        long workerId = -1;

        long v = System.currentTimeMillis() - START_TIME;
        Long sequence = getSequence();

        v = v << 5;
        v = v + subCode;

        v = v << 5;
        v = v + workerId;

        v = v << 12;

        v = v + sequence;

        return  v;
    }


}
